import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Form, Spin, Tooltip, message } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import pageStyles from '@/common/pageLayout.less';
import { downloadTemplate, getFileNameNotType, getLoadMapList, getTenantID, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import MyIcon from '@/components/MyIcon';
import { formatDecimal } from '../../Acommon';
import moment from 'moment';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 引入上下文 */
  const { styleFixCls, infoObj } = useContext(ChangeControllerContext);

  const [isPass, setIsPass] = useState<boolean>(false); // 是否通过线下审批

  /** 采购方式字典services */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];
  const { loadMapInfo: dictionaryData, mapLoading } = getLoadMapList(loadMdicIds);
  const purchaseFs = dictionaryData?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];

  const [changeFromRef] = Form.useForm(); // 表单实例

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    let treeSearch = '';
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: <div id={item?.id}>{titleTree}</div>,
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: <div id={item?.id}>{titleTree}</div>,
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  useEffect(() => {
    if (infoObj?.id) {
      setFieldsValue({
        ...infoObj,
        expectSum: formatDecimal(infoObj?.expectSum),
        applyTime: moment(infoObj?.applyTime).format('YYYY-MM-DD'),
      });
    }
  }, [infoObj]);

  // 表格表单配置信息
  const [config, { setFieldsValue }] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        label: '变更采购方式申请',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '申请日期',
        field: 'applyTime',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
        required: false,
      },
      {
        label: '流水单号',
        field: 'changeCode',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请人',
        field: 'createrName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '联系电话',
        field: 'applyPhone',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请部门/单位',
        field: 'createDepartmentName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '职务岗位',
        field: 'applyPositionName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '采购项目名称',
        field: 'purchProjectName',
        component: 'Input',
        disabled: true,
      },
      {
        label: '标包名称',
        field: 'packName',
        component: 'Input',
        disabled: true,
      },
      {
        label: '变更前采购方式',
        field: 'procureDraft',
        component: 'TreeSelect',
        treeData: orgTreeData(purchaseFs),
        disabled: true,
      },
      {
        label: '拟采用采购方式',
        placeholder: '请选择拟采用采购方式',
        field: 'procureReal',
        component: 'TreeSelect',
        required: true,
        treeData: orgTreeData(purchaseFs),
        disabled: true,
      },
      {
        label: '预算金额',
        field: 'expectSum',
        component: 'Input',
        disabled: true,
        contentAfter: '元',
      },
      {
        label: '审批方式',
        field: 'applyFlag',
        component: 'Render',
        colSpan: 1,
        required: true,
        slotRender: (text) => {
          return (
            <TagSelect
              colSpan={24}
              formLabel={''}
              formName={'applyFlag'}
              defalultKeys={Number(text)}
              onChange={(val) => setIsPass(Boolean(val))}
              radioList={[
                {
                  value: 0,
                  name: '线上',
                },
                {
                  value: 1,
                  name: '线下',
                },
              ]}
              radioDisabled={true}
            />
          );
        },
      },
      {
        label: '相关附件',
        field: 'applyURL',
        placeholder: '请上传相关附件',
        component: 'Render',
        colSpan: 2,
        required: isPass ? true : false,
        slotRender: (text) => {
          return (
            <>
              {text && infoObj?.id ? (
                <span style={{ marginLeft: '8px' }}>
                  {infoObj?.['applyURL'] && splitFileUrl(infoObj?.['applyURL']).length > 0
                    ? splitFileUrl(infoObj?.['applyURL'])?.map((e, i) => {
                        return (
                          <Tooltip title={e.attachName} key={new Date().getTime() * 5456245 + e?.attachName}>
                            <a
                              onClick={() => {
                                message.success('下载中，请稍后...');
                                downloadTemplate('/purchaseSourceChangeController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                              }}
                            >
                              <MyIcon type="icon-file-text-fill" />
                              &nbsp;
                              {getFileNameNotType(e.attachName, 8)}
                            </a>
                          </Tooltip>
                        );
                      })
                    : '--'}
                </span>
              ) : (
                <span style={{ color: '#ccc', marginLeft: '8px' }}>--</span>
              )}
            </>
          );
        },
      },
      {
        label: '采购方式变更理由',
        field: 'applyInfo',
        component: 'InputTextArea',
        required: true,
        showCount: true,
        allowClear: true,
        maxLength: 800,
        autoSize: { minRows: 6, maxRows: 8 },
        colSpan: 2,
        disabled: true,
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 100px' }}>
            <Spin spinning={mapLoading}>
              <Descriptions config={config} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
